package dnl.jexem.prcs;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import au.com.bytecode.opencsv.CSVReader;
import dnl.jexem.cmd.CommandExecution;
import dnl.jexem.cmd.CommandExecutionFactory;

/**
 * 
 * @author Daniel Orr
 *
 */
public class WindowsCommandsProcessOperations implements ProcessOperations {

	@Override
	public ProcessInfo getProcess(int pid) {
		throw new UnsupportedOperationException();
	}
	
	@Override
	public List<ProcessInfo> grepProcesses(String grepExpression) {
		throw new UnsupportedOperationException();
	}

	@Override
	public List<ProcessInfo> getProcesses() {
		CommandExecution commandExecution = CommandExecutionFactory.createLocalCommandExecution(
				"tasklist", "/v", "/fo", "CSV");
		commandExecution.executeCommand(3000);
		if (commandExecution.getExitStatus() != 0) {
			System.err.println("Error executing: " + commandExecution.getFullCommand());
			return Collections.emptyList();
		}
		String output = commandExecution.getOutput();
		CSVReader reader = new CSVReader(new StringReader(output));
		List<ProcessInfo> processes = new ArrayList<ProcessInfo>();
		try {
			// first line is column titles and thus we get rid of it
			String[] nextLine = reader.readNext();
			while ((nextLine = reader.readNext()) != null) {
				try {
					ProcessInfo pi = new ProcessInfo();
					pi.setCmd(nextLine[0]);
					pi.setProcessID(Integer.parseInt(nextLine[1]));
					String mem = nextLine[4];
					mem = StringUtils.remove(mem, ' ');
					mem = StringUtils.remove(mem, 'K');
					mem = StringUtils.remove(mem, ',');
					pi.setMemUsage(Integer.parseInt(mem) * 1024);
					pi.setUserID(nextLine[6]);
					processes.add(pi);
				} catch (Exception e) {
					// System.err.println("err parsing line> "+ArrayUtils.toString(nextLine)+"> "+e.toString());
				}

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return processes;
	}

	
	@Override
	public boolean killProcess(int pid) {
		CommandExecution commandExecution = CommandExecutionFactory.createLocalCommandExecution(
				"taskkill", "/PID", Integer.toString(pid));
		commandExecution.executeCommand(1000);
		return true;
	}

}
